<template>
    <div id="notice-detail">
        <el-row class="card-box">
            <el-card class="form-box">
                <fieldset class="fieldset">
                    <legend>待办规则信息</legend>
                    <div>
                        <el-form :label-position="labePosition" label-width="127px" size="mini">
                            <el-row>
                                <el-col :span="5">
                                    <el-form-item label="规则编码:">
                                        <el-input v-model="ruleForm.cRuleId" :disabled="true" :title="ruleForm.cRuleId" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="规则名称:">
                                        <el-input v-model="ruleForm.ruleName" :disabled="true" :title="ruleForm.ruleName" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="7">
                                    <el-form-item label="待办生成时间:">
                                        <el-input
                                            :value="dateFormatter(ruleForm.dCtDate, ruleForm.dCtTime)"
                                            :disabled="true"
                                            :title="dateFormatter(ruleForm.dCtDate, ruleForm.dCtTime)"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="待办状态:">
                                        <el-select placeholder="请选择" style="width: 100%" v-model="ruleForm.cStatus" :disabled="true">
                                            <el-option
                                                v-for="item in stateEnumStorage"
                                                :key="item.dictKey"
                                                :label="item.dictKey + ' ' + item.dictKeyName"
                                                :value="item.dictKey"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </fieldset>
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card class="form-box">
                <div>
                    <vxe-table
                        :data="dataListDetailSource"
                        :key="tableKey"
                        border
                        @checkbox-change="handleSelectionChange"
                        @checkbox-all="handleSelectionChange"
                        @sort-change="handleSelectionChange2"
                        @filter-change="handleFilterChange"
                        @resizable-change="handleResizeChange"
                        ref="xTable"
                        size="mini"
                        style="width: 100%"
                        :auto-resize="true"
                        :resizable-config="{ minWidth: '90' }"
                        :filter-config="{ remote: true }"
                        :sort-config="{ remote: true }"
                        show-header-overflow
                        :row-style="{ height: '35px' }"
                        :cell-style="{ padding: '0px' }"
                    >
                        <vxe-column type="checkbox" width="55" size="mini" align="center" :selectable="getSelectableModule" resizable> </vxe-column>
                        <vxe-column field="cStlossEventId" title="待办编号" min-width="120" show-overflow resizable> </vxe-column>
                        <vxe-column field="cFundCode" title="产品代码(名称)" min-width="160" show-overflow resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.cFundCode + '(' + scope.row.fundName + ')' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="reminderContent" title="提醒内容" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.reminderContent || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="entryTagNames" title="条目标签" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.entryTagNames || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="depositaryName" title="受托人" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.depositaryName || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="fundManagerName" title="投资经理" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.fundManagerName || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="nAccuYield" title="当前产品收益率" min-width="140" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span> {{ formatNAccuYield(scope.row.nAccuYield) }} </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="intervalRangeName" title="所在止损区间" min-width="140" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.intervalRangeName || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="stopLossTriggerType" title="触发类型" min-width="120" show-overflow resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ ThresholdType[scope.row.stopLossTriggerType] || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="entryCode" title="触发条目编号" min-width="140" show-overflow align="center" resizable> </vxe-column>
                        <vxe-column field="entryName" title="触发条目风险说明" min-width="140" show-overflow align="center" resizable> </vxe-column>
                        <vxe-column field="thresholdType" title="触警结果" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ triggerTypePojo[scope.row.thresholdType] || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cStatus" title="待办状态" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span :style="getStyle(scope.row.cStatus)">
                                    {{ stateEnum[scope.row.cStatus] || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cEventTag" title="待办标签" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.cEventTag || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cEventContent" title="待办备注" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.cEventContent || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="dCtDate" title="计算时间" min-width="120" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span> {{ dateFormatter(scope.row.dCtDate, scope.row.dCtTime) }}</span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cNoticeEntryCode" title="提醒条目编号" min-width="140" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.cNoticeEntryCode || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cNoticeEntryName" title="提醒条目风险说明" min-width="140" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ scope.row.cNoticeEntryName || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cNoticeThresholdValue" title="提醒条目控制值" min-width="140" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{
                                        numberFormatCIB(scope.row.cNoticeThresholdValue, scope.row.unit, 'thresholdValue') + unitShow(scope.row.unit)
                                    }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cNoticeResult" title="提醒条目计算结果值" min-width="140" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span>
                                    {{ numberFormatCIB(scope.row.cNoticeResult, scope.row.unit) + unitShow(scope.row.unit) }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="opUserName" title="操作人" min-width="120" show-overflow resizable> </vxe-column>
                        <vxe-column field="dOpTime" title="操作时间" min-width="160" show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span> {{ dateFormatter(scope.row.dOpDate, scope.row.dOpTime) || '--' }}</span>
                            </template>
                        </vxe-column>

                        <vxe-column title="操作" min-width="50" fixed="right">
                            <template slot-scope="scope">
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-view"
                                    topTitle="查看明细"
                                    @on-click="addTabs('lookDetail', scope.row)"
                                ></RiskIconButton>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card class="form-box">
                <fieldset class="fieldset">
                    <legend>{{ data.disType == '2' ? '已办处置信息' : '待办处置信息' }}</legend>
                    <el-form :label-position="labePosition" label-width="127px" size="mini">
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="待办标签:">
                                    <el-select placeholder="请选择" style="width: 100%" v-model="ruleForm.cEventTag" :disabled="data.disType == '2'">
                                        <el-option
                                            v-for="item in cEventTagEnum"
                                            :key="item.dictKey"
                                            :label="item.dictKey + ' ' + item.dictKeyName"
                                            :value="item.dictKey"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="待办备注:">
                                    <el-input
                                        type="textarea"
                                        :rows="2"
                                        placeholder="请输入内容"
                                        v-model="ruleForm.cEventContent"
                                        :disabled="data.disType == '2'"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </fieldset>
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card>
                <div class="btns">
                    <el-button @click="$emit('close-tab', data.name)">关闭</el-button>
                    <el-button v-if="isShowSubmit && data.disType === 1" type="primary" @click="submit('0')" :loading="btnLoading"
                        >保存待办处置信息</el-button
                    >
                    <el-button v-if="isShowSubmit && data.disType === 1" type="danger" @click="submit('1')" :loading="btnLoading">关闭待办</el-button>
                    <el-button v-if="isShowSubmit && data.disType === 2" type="danger" @click="submit('2')" :loading="btnLoading">转回待办</el-button>
                </div>
            </el-card>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { accMul, changeOptions, dateFormat, numberFormatCIB, timeFormat, unitShow } from '@/utils/tools';
import RiskEntryInputs from '@/common/components/risk-entry-inputs.vue';
import * as moment from 'moment';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import { mixins } from 'vue-class-component';
import RiskEmitter from '@/common/mixis/risk-emitter.vue';
@Component({
    name: 'DispositionListDetails',
    components: { RiskEntryInputs, RiskIconButton },
})
export default class DispositionListDetails extends mixins(RiskEmitter) {
    @Prop() data: any;
    @Prop() dataForm: any;

    numberFormatCIB = numberFormatCIB;
    unitShow = unitShow;

    private labePosition: string = 'right';

    defaultTime: any = new Date(0, 0, 0, moment().hour(), 0, 0);
    defaultTime2: any = new Date(0, 0, 0, moment().hour() + 1, 0, 0);
    limitTimeTitle: string = window.project_config.LIMIT_TIMES_TITLE || '该字段为在设置时间段内发送次数上限，非重复发送邮件次数';
    private ruleForm: any = {
        cRuleId: '',
        ruleName: '',
        dCtTime: '',
        dCtDate: '',
        cStatus: '',
        cEventTag: '0',
        cEventContent: '',
        cstlossEventDetailId: '',
        cstlossEventId: '',
    };
    private dataListDetailSource: any[] = []; // 待办事项详情表格数据
    private tableKey: number = 1;
    private stateEnumStorage: any[] = [
        { dictKey: '0', dictKeyName: '待处理' },
        { dictKey: '1', dictKeyName: '处理中' },
        { dictKey: '2', dictKeyName: '已处理' },
    ];
    private cEventTagEnum: any[] = [
        { dictKey: '0', dictKeyName: '紧急处理' },
        { dictKey: '1', dictKeyName: '延后处理' },
        { dictKey: '2', dictKeyName: '已完成' },
    ]; // 待办标签字典
    private stateEnum: any = {
        '0': '待处理',
        '1': '已处理',
    }; // 处理状态
    public triggerTypePojo = {
        '0': '合规',
        '1': '警告',
        '2': '送审',
        '3': '禁止',
        '4': '错误',
    } as const; // 触警结果
    private fundGroup: any[] = [];
    private fundGroupStorageEnum: any = {};
    private userStorage: any[] = [];
    private userStorageEnum: any = {};
    private showType: string = '';

    private btnLoading: boolean = false;

    private isEdit: boolean = false; // 文本是否在编辑状态

    private ThresholdType: any = {
        '0': '无',
        '1': '上升',
        '2': '下降',
        '3': '跟踪',
        '4': '恢复',
    }; // 触警类型

    private entryStorage: any[] = [];
    private entryStorageEnum: any = {};
    private entryGroupStorage: any[] = [];
    private entryGroupStorageEnum: any[] = [];
    private roleStorage: any[] = [];
    private roleStorageEnum: any = {};
    created() {}
    async mounted() {}
    // 状态样式
    private getStyle(value: string): any {
        let color = '';
        color = value == '0' ? 'red' : value == '1' ? 'green' : '';
        return { color: color };
    }

    // 时间处理
    private dateFormatter(date, time) {
        if (date || time) {
            return (date ? dateFormat(date, true) : '') + ' ' + (time ? timeFormat(time, true) : '');
        }
        return '--';
    }

    // 回调函数
    addTabs(data: any, val: any) {
        let datas: any = {};
        datas.type = data;
        datas.value = val;

        this.dispatch('Disposition', 'addTables', datas);
    }

    // 监听父组件带进来的基础数据
    @Watch('data', { immediate: true, deep: true })
    watchData(newData) {
        if (newData) {
            if (newData.content) {
                let data = JSON.parse(JSON.stringify(newData.content));
                data.dates = [String(...(data.startDate || '')), String(...(data.endDate || ''))];
                data.startTime = String(data.startTime || '');
                data.endTime = String(data.endTime || '');
                console.log(JSON.stringify('form值------------' + JSON.stringify(this.dataForm)));
                console.log('类型值------------' + newData.disType);
                this.ruleForm = this.dataForm ?? this.ruleForm;
                this.ruleForm.cstlossEventDetailId = data.cStlossEventDetailId;
                this.ruleForm.cstlossEventId = data.cStlossEventId;

                if (data.cEventTag) {
                    this.$set(this.ruleForm, 'cEventTag', data.cEventTag);
                }
                if (data.cEventContent) {
                    this.$set(this.ruleForm, 'cEventContent', data.cEventContent);
                }
                console.log(JSON.stringify('详情id------------' + this.ruleForm.cstlossEventDetailId));
                this.dataListDetailSource = [];
                this.dataListDetailSource.push(data);
            }
            this.showType = newData.type;
        }
    }

    get isShowSubmit() {
        return this.showType == 'edit';
    }

    private handleDate(val: any) {
        if (val && val.length) {
            this.ruleForm.startDate = val[0];
            this.ruleForm.endDate = val[1];
            return;
        }
        this.ruleForm.startDate = '';
        this.ruleForm.endDate = '';
    }

    private handleTime() {
        if (this.ruleForm.startTime && this.ruleForm.endTime) {
            if (this.ruleForm.startTime > this.ruleForm.endTime) {
                this.yh_message_warn('开始时间不得晚于结束时间!');
                this.ruleForm.startTime = '';
                this.ruleForm.endTime = '';
                return;
            }
        }
    }

    private getAccountControlValue(val: any) {
        this.ruleForm.fundCode = val;
    }

    private submit(status: string) {
        let statusValue = status;
        let title = '确认是否关闭待办?';
        if (!this.verify()) {
            return;
        }
        if (status === '2') {
            statusValue = '0';
            title = '确认是否转回待办?';
        }
        this.btnLoading = true;
        let url = '/htscamc/stopLossEvent/detail/update';
        let data = {
            ceventContent: this.ruleForm.cEventContent,
            ceventTag: this.ruleForm.cEventTag,
            cstatus: statusValue,
            cstlossEventDetailId: this.ruleForm.cstlossEventDetailId,
            cstlossEventId: this.ruleForm.cstlossEventId,
        };
        if (status === '1' || status === '2') {
            this.$confirm(title, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.$axios({ url, method: 'post', data })
                        .then((res: any) => {
                            this.btnLoading = false;
                            this.yh_message_success('操作成功！');
                            this.$emit('close-tab', this.data.name);
                        })
                        .catch(() => {
                            this.btnLoading = false;
                        });
                })
                .catch(() => {
                    this.yh_message_info('已取消操作');
                    this.btnLoading = false;
                });
        } else {
            this.$axios({ url, method: 'post', data })
                .then((res: any) => {
                    this.btnLoading = false;
                    this.yh_message_success('操作成功！');
                    this.$emit('close-tab', this.data.name);
                })
                .catch(() => {
                    this.btnLoading = false;
                });
        }

        //  this.ruleForm.limitTimes = this.ruleForm.limitTimes ? Number(this.ruleForm.limitTimes) : null;
    }

    private verify() {
        // if (!this.ruleForm.cEventContent) {
        //     this.yh_message_warn('待办备注不能为空！');
        //     return false;
        // }
        if (!this.ruleForm.cEventTag) {
            this.yh_message_warn('待办标签不能为空！');
            return false;
        }
        return true;
    }

    /**
     * 获取下拉数据 根据已选择数据排序
     * @param selectedData 已选择的数据
     * @param optionsData 所有选项数据
     * @param key 排序的键值
     * @returns 排序后的结果数组
     */
    sortCheckOptions(selectedData: any[], optionsData: any[], key: string): any[] {
        const selectedOptions = selectedData.map(item => optionsData.find(option => item === option[key])).filter(Boolean);
        // 将已选中项进行排序 (根据角色[0]排在一起)
        selectedOptions.sort((a, b) => Number(b.sortId.replace('YH', '')) - Number(a.sortId.replace('YH', '')));
        const otherOptions = optionsData.filter(option => !selectedOptions.includes(option));
        const sortedOptions = [...selectedOptions, ...otherOptions];

        const map = new Map();
        for (const item of sortedOptions) {
            if (!map.has(item[key])) {
                map.set(item[key], item);
            }
        }
        const newArr = [...map.values()];
        return newArr;

        // return [...new Set(sortedOptions.map(option => option[key]))].map(key => sortedOptions.find(option => option[key] === key));
    }

    private handleEdit() {
        this.isEdit = !this.isEdit;
    }

    private onInput(e) {
        e.target.value = e.target.value.replace(/[^0-9]/g, '');
    }

    /**
     * 当前产品收益率 %展示
     */
    formatNAccuYield(val): string {
        if (val || val == 0) {
            return accMul(val, 100) + '%';
        }
        return '--';
    }
}
</script>
<style lang="scss" scoped>
#notice-detail {
    //  height: 100%;
    display: flex;
    flex-direction: column;
    height: 100vh; /* 设置父容器高度为视口高度 */
    .dashed-border-header {
        border-top: 1px dashed #999;
        text-align: center;
    }

    .card-box {
        flex: 1; /* 让每个el-row自动撑满剩余空间 */
        margin-bottom: 10px;
        // margin-top: 30px;
        .fieldset {
            border: 2px dashed #a39f9f;
            margin-bottom: 1px;
            margin-top: 1px;
            margin-left: 1px;
        }
        .form-box {
            .left-label {
                /deep/ .el-form-item__label {
                    width: 80px !important;
                }
                /deep/ .el-form-item__content {
                    margin-left: 80px !important;
                }
            }
            /deep/ .el-input--mini {
                width: 70%;
            }
            /deep/ .el-form-item__label {
                color: black;
            }
            /deep/ .el-date-editor .el-range-separator {
                padding: 0 15px;
            }
        }
        .email-title {
            margin-bottom: 20px;
            h2 {
                text-align: center;
                font-size: 1.5em;
            }
            .title-ipt {
                width: 200px;
                margin: 0 auto;
                /deep/ .el-input__inner {
                    font-size: 1.5em;
                }
            }
        }
        .text-box {
            font-family: monospace;
            font-size: inherit;
            white-space: pre-wrap;
        }
        .link-box {
            display: inline-block;
            float: right;
            padding-right: 10px;
            /deep/ .el-link {
                margin: 0 5px;
            }
        }
        .btns {
            display: inline;
            float: right;
            padding-bottom: 20px;
        }

        /deep/ .el-checkbox-group {
            height: 25px;
            .el-checkbox {
                margin-right: 5px;

                .el-checkbox__label {
                    padding-left: 5px;
                }
            }
        }

        .h3-style {
            span {
                margin: 0 30px 0 10px;
                color: red;
            }
        }
    }
}
.left-label2 {
    /deep/ .el-form-item__label {
        width: 95px !important;
    }
    /deep/ .el-form-item__content {
        margin-left: 95px !important;
    }
}

// /deep/ .el-input--suffix .el-input__inner {
//     height: 28px !important;
// }

// /deep/ .el-select__tags {
//     height: 28px !important;
// }

// /deep/ .el-select__tags span.el-tag:first-child .el-select__tags-text {
//     width: calc(100% - 18px);
//     overflow: hidden;
//     text-overflow: ellipsis;
//     white-space: nowrap;
//     display: inline-block;
// }

// /deep/ .el-select__tags span.el-tag:first-child {
//     width: 45%;

//     .el-tag__close {
//         top: -3px;
//     }
// }

// /deep/ .el-select__tags span.el-tag:nth-child(2) {
//     padding: 0 5px;
// }
</style>
